package com.atguigu.eduservice.service.impl;

import com.aiguigu.commonutils.JwtUtils;
import com.aiguigu.commonutils.ResultCode;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.feign.UcenterService;
import com.atguigu.eduservice.mapper.EduCommentMapper;
import com.atguigu.eduservice.service.EduCommentService;
import com.atguigu.servicebase.entity.vo.UcenterMemberVo;
import com.atguigu.servicebase.exceptionhandler.GuLiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author Y丶HS练习谷粒商城
 * @since 2022-10-09
 */
@Service
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {

    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 用户服务
     */
    @Resource
    private UcenterService ucenterService;
    @Override
    public Map<String, Object> listEntityByCourseId(Page<EduComment> commentPage, String courseId) {
        // 组装条件
        LambdaQueryWrapper<EduComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .orderByDesc(EduComment::getGmtCreate)
                .eq(StringUtils.hasLength(courseId), EduComment::getCourseId,courseId);
        // 查询
        this.page(commentPage,queryWrapper);
        // 返回结果集
        List<EduComment> commentList = commentPage.getRecords();
        Map<String, Object> map = new HashMap<>(7);
        map.put("info", commentList);
        map.put("current", commentPage.getCurrent());
        map.put("pages", commentPage.getPages());
        map.put("size", commentPage.getSize());
        map.put("total", commentPage.getTotal());
        map.put("hasNext", commentPage.hasNext());
        map.put("hasPrevious", commentPage.hasPrevious());
        return map;
    }

    @Override
    public void saveEntity(EduComment entity, String token) {

        if(StringUtils.isEmpty(token)){
            throw new GuLiException(ResultCode.NO_LOGIN,"未登录，请登录在操作");
        }
        String redisToken = (String) redisTemplate.opsForValue().get(token);

        // 获取用户id
        String userId = JwtUtils.getIdByToken(redisToken);
        // 获取用户信息
        UcenterMemberVo userInfo = ucenterService.getUserInfo(userId);
        // 组装参数
        entity.setNickname(userInfo.getNickname());
        entity.setAvatar(userInfo.getAvatar());
        this.save(entity);
    }
}
